export function _N(num, rank = 0) {
  typeof num !== 'number' && (num = 0);
  return parseFloat(num.toFixed(rank));
}
export function omitNil(obj) {
  return _.omitBy(obj, _.isNil);
}
export function _H(head) {
  return head || '/xs_qm/img/common/default_head.png';
}
export function log(...params) {
  console.log("debug[================]:", ...params);
}
export function _name(user = {}, defaultValue = '') {
  if (!user.phone) {
    return user.name || defaultValue;
  }
  return `${user.name || defaultValue}(${user.phone})`;
}
export function _date(time = '') {
  return time.slice(0, 10);
}
export function sleep(ms) {
  return new Promise(resolve => { setTimeout(resolve, ms); });
}
export async function until(test, ms = 100) {
  while (!test()) {
    await sleep(ms);
  }
}
// limitStr('请你去123456789', 12) -> '请你去123...'
export function limitStr(text = '', n, append = '...') {
  let realLength = 0, len = text.length, preLen = -1, charCode = -1, needCut = false, appendLen = append.length;
  for (let i = 0; i < len; i++) {
    charCode = text.charCodeAt(i);
    if (charCode >= 0 && charCode <= 128) {
      realLength += 1;
    } else {
      realLength += 2;
    }
    if (preLen === -1 && realLength >= n) {
      preLen = i + 1;
    } else if (realLength > n + appendLen) {
      needCut = true;
      break;
    }
  }
  if (needCut) {
    text = text.substr(0, preLen) + append;
  }
  return text;
}

export function toThousands(num) {
  return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
}

export function getPercentages(list) {
  const sum = _.sum(list);
  return list.map((v) => Math.round(v * 100 / sum) + '%');
}
export function numberParser(precision) {
  return (v) => {
    v = v.replace(/[^\d-.]+/g, '');
    const reg = /([^.]*)\.(.*)/;
    const m = v.match(reg);
    if (!m) {
      return v;
    }
    return m[1] + '.' + (m[2].replace(/\./g, '').slice(0, precision));
  };
}
export function formatPhoneList(phoneList = '', phone = '') {
  phoneList = phone + ';' + phoneList.replace('；', ';');
  phoneList = _.uniq(_.filter(_.map(phoneList.split(';'), m => m.trim()), o => !!o));
  return phoneList.join(';');
}
export function parseJSON(str, defaultValue) {
  try {
    return JSON.parse(str);
  } catch (e) {
    console.log('json parse error:', e.message);
    return defaultValue;
  }
}
export function evalCode(str) {
  try {
    return { value: (new Function(`return ${str}`))() };
  } catch (e) {
    console.log('eval error:', e.message);
    return { error: true, message: e.message || 'evel错误' };
  }
}
export function urlParam(obj, key) {
  if (typeof obj !== 'object') {
    return encodeURI(`${key}=${obj}`);
  } else {
    obj = _.omitBy(obj, o => _.isNil(o));
  }
  const list = [];
  for (let i in obj) {
    const v = obj[i];
    const j = key ? `${key}[${i}]` : i;
    if (v instanceof Array) {
      for (let k in v) {
        list.push(urlParam(v[k], `${j}[${k}]`));
      }
    } else {
      list.push(urlParam(v, j));
    }
  }
  return list.join('&');
}
function pareUrlParam(search) {
  const params = {};
  search && search.split('&').forEach(o => {
    const split = o.indexOf('=');
    let val, key;
    if (split === -1) {
      key = o;
    } else {
      key = o.substr(0, split);
      val = o.substr(split + 1);
    }
    if (val === undefined) {
      if (key[0] === '!') {
        key = key.slice(1);
        val = false;
      } else {
        val = true;
      }
    } else if (val === 'true') {
      val = true;
    } else if (val === 'false') {
      val = false;
    } else if (/^-?\d+(\.\d+)?$/.test(val)) { // 数字
      val = val * 1;
    } else if (/^'(-?\d+(\.\d+)?)|true|false'$/.test(val)) {
      val = val.replace(/^'|'$/g, '');
    }
    Object.assign(params, { [key]: val });
  });
  return params;
}
export function pareUrl(url, param = {}) {
  const list = url.split('?');
  const state = pareUrlParam(list[1]);
  return { pathname: list[0], state: { ...state, ...param } };
}
export function getWindowLocationSearch() {
  if (typeof window === 'undefined') {
    return {};
  }
  return pareUrlParam(decodeURIComponent(window.location.search.slice(1)));
}
export function getSize(number) {
  if (number < 1024) {
    return _N(number) + 'B';
  } else if (number < 1024 * 1024) {
    return _N(number / 1024) + 'KB';
  } else {
    return _N(number / (1024 * 1024)) + 'MB';
  }
}
export function randomColor() {
  return '#' + ('00000' + ((Math.random() * 16777215 + 0.5) >> 0).toString(16)).slice(-6);
}
export function download(url, name) {
  const a = document.createElement('a');
  name && (a.download = name);
  if (url.match(/\?/g)) {
    a.href = url + '&download=true';
  } else {
    a.href = url + '?download=true';
  }
  a.style.display = 'none';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}
function createInput(name, value) {
  const el = document.createElement("input");
  el.type = "hidden";
  el.name = name;
  if (value != null) {
    el.value = value;
  }
  return el;
}
export function postForm(url, data) {
  const form = document.createElement("form");
  form.action = url;
  form.method = "post";
  form.style.display = "none";
  for (let key in data) {
    form.appendChild(createInput(key, data[key]));
  }
  document.body.appendChild(form);
  form.submit();
  document.body.removeChild(form);
}
export function loadJsCode(code, callback) {
  var script = document.createElement("script");
  script.type = "text/javascript";
  if (typeof callback != "undefined") {
    if (script.readyState) {
      script.onreadystatechange = function () {
        if (script.readyState == "loaded" || script.readyState == "complete") {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else {
      script.onload = function () {
        callback();
      };
    }
  }
  script.textContent = code;
  document.body.appendChild(script);
}
export function loadJsCodeSync(code) {
  return new Promise(async (resolve) => {
    loadJsCode(code, function () {
      resolve();
    });
  });
}
export function fileTypeImage(file) {
  if (file.file) {
    const obj = file.file;
    const fileName = obj.split('/')[obj.split('/').length - 1];
    const suffix = fileName.split('.')[1];
    const word = ['doc', 'docx'];
    const excel = ['xls', 'xlsx'];
    const image = ['png', 'jpg', 'jpeg'];
    const mp3 = ['mp3', 'wma', 'wav', 'midi', 'ape', 'flac'];
    const ppt = ['ppt', 'pptx'];
    const video = ['avi', 'AVI', 'mov', 'rmvb', 'rm', 'FLV', 'mp4', '3GP'];
    const _package = ['rar', 'zip'];
    if (_.includes(word, suffix)) {
      return '/xs_qm/img/skydrive/word.png';
    } else if (_.includes(excel, suffix)) {
      return '/xs_qm/img/skydrive/excel.png';
    } else if (_.includes(image, suffix)) {
      return file.file;
    } else if (_.includes(ppt, suffix)) {
      return '/xs_qm/img/skydrive/ppt.png';
    } else if (_.includes(mp3, suffix)) {
      return '/xs_qm/img/skydrive/mp3.png';
    } else if (_.includes(video, suffix)) {
      return '/xs_qm/img/skydrive/video.png';
    } else if (_.includes(_package, suffix)) {
      return '/xs_qm/img/skydrive/package.png';
    } else {
      return '/xs_qm/img/skydrive/txt.png';
    }
  } else {
    return '/xs_qm/img/skydrive/folder.png';
  }
}
export function timeConversion(timelong) {
  if (timelong) {
    const ss = parseInt((timelong % 3600) % 60);
    const mm = parseInt((timelong % 3600) / 60);
    const hh = parseInt(timelong / 3600);
    if (timelong < 60) {
      return (ss + '秒');
    } else if (timelong < 3600) {
      return mm ? (mm + '分' + ss + '秒') : (ss + '秒');
    } else {
      return !ss && !mm ? (hh + '小时') : !ss ? (hh + '小时' + mm + '分') : (hh + '小时' + mm + '分' + ss + '秒');
    }
  } else {
    return ('0秒');
  }
}
export function timePoint(time) {
  let now = moment(), date = moment(time);
  if (now.isSame(date, 'day')) {
    return date.format('HH:mm');
  } else if (now.startOf('day').diff(moment(time).startOf('day'), 'day') == 1) {
    return date.format('昨天');
  }
  return date.format('M月D日');
}
